package com.simen.downloader;

import android.os.Handler;
import android.util.Log;

import com.simen.downloader.exception.ThreadCancelledException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by zhangming on 16/5/16.
 */
abstract class ParentThread implements Runnable {

    final DownloadInfor downloadInfor;
    final DownloadEngine engine;
    ParcelFile cachefile = null;

    public ParentThread(DownloadEngine engine, DownloadInfor downloadInfor) {
        this.downloadInfor = downloadInfor;
        this.engine = engine;
        this.cachefile = new ParcelFile();
    }

    protected boolean waitIfPaused() {
        AtomicBoolean pause = engine.getPause();
        if (pause.get()) {
            synchronized (engine.getPauseLock()) {
                if (pause.get()) {
                    try {
                        engine.getPauseLock().wait();
                    } catch (InterruptedException e) {
                        return true;
                    }
                }
            }
        }
        return isListenerRecycled();
    }

    protected void checkListenerRecycled() throws ThreadCancelledException {
        if (isListenerRecycled()) {
            throw new ThreadCancelledException();
        }
    }

    protected boolean isListenerRecycled() {
        return downloadInfor == null || downloadInfor.isCollected();
    }

    /**
     * @throws ThreadCancelledException if current task was interrupted
     */
    protected void checkThreadInterrupted() throws ThreadCancelledException {
        if (isThreadInterrupted()) {
            throw new ThreadCancelledException();
        }
    }

    /**
     * @return <b>true</b> - if current task was interrupted; <b>false</b> - otherwise
     */
    protected boolean isThreadInterrupted() {
        if (Thread.interrupted()) {
            return true;
        }
        return false;
    }

    protected DownloadService.DownloadStatus getStatus(String key, String fileRealUrl, long
            createtime, long lasttime, long current, long total, int progress, String fileName,
                                                       String localPath) {
        cachefile.setParamers(key, fileRealUrl, createtime,
                lasttime, current, total, progress, fileName, localPath);
        return new DownloadService.DownloadStatus(cachefile, downloadInfor.loader.get());
    }

    public static void writeStatus(String logFilePath, ParcelFile cachefile) {
        //保存下载信息
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(logFilePath));
            StorageFile file = new StorageFile();
            file.clone(cachefile);
            objectOutputStream.writeObject(file);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
            } catch (IOException e) {

            }
        }
    }

    /**
     * catch the exception,and report to the listener
     *
     * @param e Exception
     */
    protected void catchExecption(Handler handler, final String key, final Exception e) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!DownloadThread.isListenerRecycled(downloadInfor)) {
                    downloadInfor.loader.get().Exception(key, e);
                }
            }
        }, 0);
    }
}
